﻿using Microsoft.Extensions.DiagnosticAdapter;
using System.Diagnostics;

namespace DiagnosticSourceDemo.Host
{
    public sealed class ExampleDiagnosticObserver : IObserver<DiagnosticListener>,
        IObserver<KeyValuePair<string, object>>
    {
        private readonly ServiceProvider _serviceProvider;
        private readonly List<IDisposable> _subscriptions = new List<IDisposable>();

        public ExampleDiagnosticObserver(IServiceCollection serviceCollection)
        {
            _serviceProvider = serviceCollection.BuildServiceProvider();
        }

        public void OnCompleted()
        {
        }

        public void OnError(Exception error)
        {
        }

        public void OnNext(KeyValuePair<string, object> value)
        {
            Write(value.Key, value.Value);
        }

        public void OnNext(DiagnosticListener value)
        {
            Console.WriteLine("OnNext: " + value.Name);

            if (value.Name == "HttpHandlerDiagnosticListener")
            {
                var subscription = value.SubscribeWithAdapter(this);
                _subscriptions.Add(subscription);
            }
        }

        [DiagnosticName("System.Net.Http.Request")]
        public void HttpRequest(HttpRequestMessage request)
        {
            var httpContextAccessor = _serviceProvider.GetService<IHttpContextAccessor>();
            var httpContext = httpContextAccessor.HttpContext;
            Console.WriteLine($"request url: {httpContext.Request.Path},method: {httpContext.Request.Method}");
        }

        [DiagnosticName("System.Net.Http.Response")]
        public void HttpResponse(HttpResponseMessage response)
        {
        }

        private void Write(string name, object value)
        {
            Console.WriteLine(name);
            Console.WriteLine(value);
            Console.WriteLine();
        }
    }
}
